//
//  WEXOAuthViewController.swift
//  microBlog
//
//  Created by apple on 16/4/19.
//  Copyright © 2016年 Hill. All rights reserved.
//

import UIKit
import SVProgressHUD

let WB_APP_KEY = "1336075890"

let WB_REDIRECT_URI = "http://www.baidu.com/"

let WB_APP_SECRET = "f535e5d4033d624ccad804392593a7db"



class WEXOAuthViewController: UIViewController{
    
    
    // MARK: - 准备OAuth登录界面
    override func loadView() {
        
        self.view = webView
        //让webView加载登录页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APP_KEY)&redirect_uri=\(WB_REDIRECT_URI)"
        
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
    }
    
    // MARK: - 设置navbar的左右按钮和标题
    func setupUI() {
        title = "登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "Close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "AutoStuff")
        
        
    }
    
    // MARK: - barButtonItem点击响应事件
    @objc private func Close() {
        
        dismissViewControllerAnimated(true, completion: nil)
        
        
    }
    
    @objc private func AutoStuff() {
        
        let accountString = "document.getElementById('userId').value='18868944819';document.getElementById('passwd').value='xifanbaichi'"
        webView.stringByEvaluatingJavaScriptFromString(accountString)
        
    }
    
    // MARK: - 加载一个webView
    private lazy var webView: UIWebView = {
        
        let wbView = UIWebView()
        
        wbView.delegate = self
        
        return wbView
    }()
    
    
}

extension WEXOAuthViewController: UIWebViewDelegate {
    
    
    
    // MARK: -询问是否需要记载回调页
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL else {
            
            return false
        }
        
        //        如果url中有回调页
        if url.absoluteString.hasPrefix(WB_REDIRECT_URI) {
            
//            print(url.query)
           
            //            如果url中包含 ‘code =’ .query 代表 ？ 后面的
            if let q = url.query where q.containsString("code="){
                
                //截取授权码
                let code = q.substringFromIndex("code=".endIndex)
                
//                print(code)
                
                
                //  加载accessToken
                
                WEXUserAccountViewModel.sharedViewModel.loadAccessToken(code, finished: { (isSuccess) -> () in
                    
                    if isSuccess {
                        
                        
                        self.dismissViewControllerAnimated(false, completion: { () -> Void in
                            
                            NSNotificationCenter.defaultCenter().postNotificationName(WEXChangeRootVCNotification, object: nil)
                        })
                        
//                    print("打开欢迎界面")
                        
                    }else{
                        
                        
                    }
                    
                    
                })
                
                
            }
            
            return false
        }
        
        return true
    }

    
    
}

